/**-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=页面前端验证引擎-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 * @author http://www.position-relative.net
 * @overide monlyu
 * @version  1.6.2 beta
 * @see
 * jquery.validationEngine-cn.js (语言包)
 * jqeury.js js文件
 */
var SelfDef = {
	/**错误信息的提示*/
	msg: '验证规则文件未找到',
	/** 错误信息位置：topLeft, topRight, bottomLeft, centerRight, bottomRight */
	postion: 'topRight',
	/**无ID属性错误提示信息*/
	noIDmsg: function(obj){
		return '字段无ID属性' + $(caller).attr("name") + " " + $(caller).attr("class");
	},
	noJsonMsg: '未能成功提交，并且json无任何返回值',
	imgError: true,
	imgUrl: '../common/images/base/noright.png'
};
(function($){
	$.fn.validationEngine = function(settings){
		if ($.validLangEng) {
			allRules = $.validLangEng.allRules;
		} else {
			$.validationEngine.debug(SelfDef.msg);
		}
		settings = jQuery.extend({
			allrules: allRules,
			validationEventTriggers: "blur",
			inlineValidation: true,
			returnIsValid: false,
			animateSubmit: true,
			unbindEngine: true,
			ajaxSubmit: false,
			promptPosition: SelfDef.postion,
			success: false,
			failure: function(){
			}
		}, settings);
		$.validationEngine.settings = settings;
		$.validationEngine.ajaxValidArray = new Array();
		var callerAry = [];//存放左右Call的数组
		if (settings.inlineValidation == true) {
			if (!settings.returnIsValid) {
				allowReturnIsvalid = false;
				$(this).find("[class*=rule]").not("[type=checkbox]").bind(settings.validationEventTriggers, function(caller){
					_inlinEvent(this);
				})
				$(this).find("[class*=rule][type=checkbox]").bind("click", function(caller){
					_inlinEvent(this);
				})
				firstvalid = false;
			}
			function _inlinEvent(caller){
				$.validationEngine.settings = settings;
				if ($.validationEngine.intercept == false || !$.validationEngine.intercept) {
					$.validationEngine.onSubmitValid = false;
					$.validationEngine.loadValidation(caller);
				} else {
					$.validationEngine.intercept = false;
				}
			}
		}
		if (settings.returnIsValid) {
			if ($.validationEngine.submitValidation(this, settings)) {
				return false;
			} else {
				return true;
			}
		}
		$(this).bind("submit", function(caller){
			$.validationEngine.onSubmitValid = true;
			$.validationEngine.settings = settings;
			if ($.validationEngine.submitValidation(this, settings) == false) {
				if ($.validationEngine.submitForm(this, settings) == true) {
					return false;
				}
			} else {
				settings.failure && settings.failure();
				return false;
			}
		})
	};
	$.validationEngine = {
		defaultSetting: function(caller){
			if ($.validLangEng) {
				allRules = $.validLangEng.allRules;
			} else {
				$.validationEngine.debug(SelfDef.msg);
			}
			settings = {
				allrules: allRules,
				validationEventTriggers: "blur",
				inlineValidation: true,
				returnIsValid: false,
				animateSubmit: true,
				unbindEngine: true,
				ajaxSubmit: false,
				promptPosition: SelfDef.postion,
				success: false,
				failure: function(){
				}
			}
			$.validationEngine.settings = settings;
		},
		loadValidation: function(caller){
			if (!$.validationEngine.settings) {
				$.validationEngine.defaultSetting()
			}
			rulesParsing = $(caller).attr('class');
			rulesRegExp = /\[(.*)\]/;
			getRules = rulesRegExp.exec(rulesParsing);
			str = getRules[1];
			pattern = /\W+/;
			result = str.split(pattern);
			var validateCalll = $.validationEngine.validateCall(caller, result)
			return validateCalll;
		},
		validateCall: function(caller, rules){
			var promptText = "";
			if (!SelfDef.imgError) {
				if (!$(caller).attr("id")) {
					$.validationEngine.debug(SelfDef.noIDmsg(caller));
				}
			}
			caller = caller;
			ajaxValidate = false;
			var callerName = $(caller).attr("name");
			$.validationEngine.isError = false;
			$.validationEngine.showTriangle = true;
			callerType = $(caller).attr("type");
			for (i = 0; i < rules.length; i++) {
				switch (rules[i]) {
					case "optional":
						if (!$(caller).val()) {
							$.validationEngine.closePrompt(caller);
							return $.validationEngine.isError;
						}
						break;
					case "required":
						_required(caller, rules);
						break;
					case "cusm":
						_customRegex(caller, rules, i);
						break;
					case "length":
						_length(caller, rules, i);
						break;
					case "email" : case 'date' : case 'number': case 'noSpecChar': case 'letter':
						_customRegex(caller,rules,i,rules[i]);
					break;
					case "maxCheck":
						_maxCheckbox(caller, rules, i);
						groupname = $(caller).attr("name");
						caller = $("input[name='" + groupname + "']");
						break;
					case "minCheck":
						_minCheckbox(caller, rules, i);
						groupname = $(caller).attr("name");
						caller = $("input[name='" + groupname + "']");
						break;
					case "confirm":
						_confirm(caller, rules, i);
						break;
					default:
				};
			};
			radioHack();
			if ($.validationEngine.isError == true) {
				linkTofield = $.validationEngine.linkTofield(caller);
				if (SelfDef.imgError) {
					($($.validationEngine.getImgTagId(caller)).size() == 0) ? $.validationEngine.buildImgTag(caller, promptText, 'error') : $.validationEngine.updateImgTag(caller, promptText);
				} else {
					($("div." + linkTofield).size() == 0) ? $.validationEngine.buildPrompt(caller, promptText, "error") : $.validationEngine.updatePromptText(caller, promptText);
				}
			} else {
				if (SelfDef.imgError) {
					$.validationEngine.closeImgTag(caller);
				} else {
					$.validationEngine.closePrompt(caller);
				}
			}
			function radioHack(){
				if ($("input[name='" + callerName + "']").size() > 1 && (callerType == "radio" || callerType == "checkbox")) {
					caller = $("input[name='" + callerName + "'][type!=hidden]:last");
					$.validationEngine.showTriangle = false;
				}
			}
			/** 必填的验证
			 * @param {Object} caller 调用者
			 * @param {Object} rules 规则
			 */
			function _required(caller, rules){
				callerType = $(caller).attr("type");
				if (callerType == "text" || callerType == "password" || callerType == "textarea") {
					if (!$(caller).val()) {
						$.validationEngine.isError = true;
						promptText += $.validationEngine.settings.allrules[rules[i]].alertText + "<br />";
					}
				}
				if (callerType == "radio" || callerType == "checkbox") {
					callerName = $(caller).attr("name");
					if ($("input[name='" + callerName + "']:checked").size() == 0) {
						$.validationEngine.isError = true;
						if ($("input[name='" + callerName + "']").size() == 1) {
							promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe + "<br />";
						} else {
							promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple + "<br />";
						}
					}
				}
				if (callerType == "select-one") {
					if (!$(caller).val()) {
						$.validationEngine.isError = true;
						promptText += $.validationEngine.settings.allrules[rules[i]].alertText + "<br />";
					}
				}
				if (callerType == "select-multiple") {
					if (!$(caller).find("option:selected").val()) {
						$.validationEngine.isError = true;
						promptText += $.validationEngine.settings.allrules[rules[i]].alertText + "<br />";
					}
				}
			}
			/**
			 * 自定义正则表达式验证
			 * @param {Object} caller 验证的字段
			 * @param {Object} rules 规则
			 * @param {Number} position 当前的位置
			 * @param {Number} value 当前的位置
			 */
			function _customRegex(caller, rules, position,value){
				if(value){
					customRule = value;
				}else{
					customRule = rules[position + 1];
				}
				pattern = eval($.validationEngine.settings.allrules[customRule].regex);
				if (!pattern.test($(caller).attr('value'))) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[customRule].alertText + "<br />";
				}
			}
			/**
			 * 验证2个字段是否为同一个值
			 * @param {Object} caller 验证的字段
			 * @param {Object} rules 规则
			 * @param {Object} position 当前的位置(必须用ID与其匹配)
			 */
			function _confirm(caller, rules, position){
				confirmField = rules[position + 1];
				if ($(caller).attr('value') != $("#" + confirmField).attr('value')) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules["confirm"].alertText + "<br />";
				}
			}
			/**
			 * 长度验证
			 * @param {Object} caller 验证的字段
			 * @param {Object} rules 规则
			 * @param {Object} position 位置
			 */
			function _length(caller, rules, position){
				startLength = eval(rules[position + 1]);
				endLength = eval(rules[position + 2]);
				feildLength = $(caller).attr('value').length;
				if (feildLength < startLength || feildLength > endLength) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules["length"].alertText + startLength + $.validationEngine.settings.allrules["length"].alertText2 + endLength + $.validationEngine.settings.allrules["length"].alertText3 + "<br />"
				}
			}
			/**
			 * Checkbox的最大选择
			 * @param {Object} caller 验证的字段
			 * @param {Object} rules 规则
			 * @param {Object} position 位置
			 */
			function _maxCheckbox(caller, rules, position){
				nbCheck = eval(rules[position + 1]);
				groupname = $(caller).attr("name");
				groupSize = $("input[name='" + groupname + "']:checked").size();
				if (groupSize > nbCheck) {
					var msgobj = $.validationEngine.settings.allrules["maxCheck"];
					$.validationEngine.showTriangle = false;
					$.validationEngine.isError = true;
					promptText += msgobj.alertText + nbCheck + msgobj.alertText2 + "<br />";
				}
			};
			/**
			 * Checkbox的最少选多少项
			 * @param {Object} caller 验证的字段
			 * @param {Object} rules 规则
			 * @param {Object} position 位置
			 */
			function _minCheckbox(caller, rules, position){
				nbCheck = eval(rules[position + 1]);
				groupname = $(caller).attr("name");
				groupSize = $("input[name='" + groupname + "']:checked").size();
				if (groupSize < nbCheck) {
					var msgObj = $.validationEngine.settings.allrules["minCheck"];
					$.validationEngine.isError = true;
					$.validationEngine.showTriangle = false;
					promptText += msgObj.alertText + " " + nbCheck + " " + msgObj.alertText2 + "<br />";
				}
			}
			return ($.validationEngine.isError) ? $.validationEngine.isError : false;
		},
		submitForm: function(caller){
			if ($.validationEngine.settings.ajaxSubmit) {
				if ($.validationEngine.settings.ajaxSubmitExtraData) {
					extraData = $.validationEngine.settings.ajaxSubmitExtraData;
				} else {
					extraData = "";
				}
				$.ajax({
					type: "POST",
					url: $.validationEngine.settings.ajaxSubmitFile,
					async: true,
					data: $(caller).serialize() + "&" + extraData,
					error: function(data, transport){
						$.validationEngine.debug("error in the ajax: " + data.status + " " + transport)
					},
					success: function(data){
						if (data == "true") {
							$(caller).css("opacity", 1)
							$(caller).animate({
								opacity: 0,
								height: 0
							}, function(){
								$(caller).css("display", "none");
								$(caller).before("<div class='ajaxSubmit'>" + $.validationEngine.settings.ajaxSubmitMessage + "</div>");
								$.validationEngine.closePrompt(".formError", true);
								$(".ajaxSubmit").show("slow");
								if ($.validationEngine.settings.success) {
									$.validationEngine.settings.success && $.validationEngine.settings.success();
									return false;
								}
							})
						} else {
							data = eval("(" + data + ")");
							if (!data.jsonValidateReturn) {
								$.validationEngine.debug(SelfDef.noJsonMsg);
							}
							errorNumber = data.jsonValidateReturn.length
							for (index = 0; index < errorNumber; index++) {
								fieldId = data.jsonValidateReturn[index][0];
								promptError = data.jsonValidateReturn[index][1];
								type = data.jsonValidateReturn[index][2];
								$.validationEngine.buildPrompt(fieldId, promptError, type);
							}
						}
					}
				})
				return true;
			}
			
			if ($.validationEngine.settings.success) {
				if ($.validationEngine.settings.unbindEngine) {
					$(caller).unbind("submit")
				}
				$.validationEngine.settings.success && $.validationEngine.settings.success();
				return true;
			}
			return false;
		},
		/**
		 * 创建自己的错误信息提示机制
		 * @param {Object} caller 调用者
		 * @param {Object} promptText 错误信息
		 * @param {Object} type 调用者类型
		 * @param {Object} ajaxed 是否采用ajax方式
		 */
		buildImgTag: function(caller, promptText, type, ajaxed){
			if (!$.validationEngine.settings) {
				$.validationEngine.defaultSetting()
			}
			var imgTag = document.createElement('img');
			$(imgTag).attr('id', $.validationEngine.getImgTagId(caller).substring(1));
			$(imgTag).attr('src', SelfDef.imgUrl);
			$(imgTag).tooltip({delay: 0,showURL: false,	bodyHandler: function(){
				return promptText; 
			},fade: 100});
			$(caller).after(imgTag);
			$(caller).addClass('errorField');
		},
		/**
		 * 更新错误信息
		 * @param {Object} caller 调用者
		 * @param {Object} promptText 错误信息
		 * @param {Object} type 调用者类型
		 * @param {Object} ajaxed 是否采用ajax方式
		 */
		updateImgTag: function(caller, promptText){
			$($.validationEngine.getImgTagId(caller)).tooltip({delay: 0,showURL: false,	bodyHandler: function(){
				return promptText; 
			},fade: 100});
		},
		getImgTagId: function(caller){
			var callerType = $(caller).attr('type');
			linkTofield = $(caller).attr('name');
			linkTofield = linkTofield.replace(/\[/g, "");
			linkTofield = linkTofield.replace(/\]/g, "");
			linkTofield = linkTofield.replace(/\./g, "");
			return '#' + $(caller).attr('type') + linkTofield;
		},
		/**
		 * 关闭错误信息
		 * @param {Object} caller
		 * @param {Object} outside
		 */
		closeImgTag: function(caller, outside){
			if (!$.validationEngine.settings) {
				$.validationEngine.defaultSetting()
			}
			var imgId = $.validationEngine.getImgTagId(caller);
			$(imgId).remove();
			$(caller).removeClass('errorField');
		},
		/**
		 * 建立错误信息的显示
		 * @param {Object} caller 字段
		 * @param {Object} promptText 错误信息
		 * @param {Object} type 类型
		 * @param {Object} ajaxed 是否采用的ajax
		 */
		buildPrompt: function(caller, promptText, type, ajaxed){
			if (!$.validationEngine.settings) {
				$.validationEngine.defaultSetting()
			}
			var divFormError = document.createElement('div');
			var formErrorContent = document.createElement('div');
			linkTofield = $.validationEngine.linkTofield(caller)
			$(divFormError).addClass("formError")
			if (type == "pass") {
				$(divFormError).addClass("greenPopup")
			}
			if (type == "load") {
				$(divFormError).addClass("blackPopup")
			}
			if (ajaxed) {
				$(divFormError).addClass("ajaxed")
			}
			$(divFormError).addClass(linkTofield);
			$(formErrorContent).addClass("formErrorContent");
			$("body").append(divFormError);
			$(divFormError).append(formErrorContent);
			if ($.validationEngine.showTriangle != false) {
				var arrow = document.createElement('div');
				$(arrow).addClass("formErrorArrow");
				$(divFormError).append(arrow);
				if ($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight") {
					$(arrow).addClass("formErrorArrowBottom")
					$(arrow).html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
				}
				if ($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight") {
					$(divFormError).append(arrow);
					$(arrow).html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
				}
			}
			$(formErrorContent).html(promptText)
			callerTopPosition = $(caller).offset().top;
			callerleftPosition = $(caller).offset().left;
			callerWidth = $(caller).width();
			inputHeight = $(divFormError).height();
			if ($.validationEngine.settings.promptPosition == "topRight") {
				callerleftPosition += callerWidth - 30;
				callerTopPosition += -inputHeight - 10;
			}
			if ($.validationEngine.settings.promptPosition == "topLeft") {
				callerTopPosition += -inputHeight - 10;
			}
			
			if ($.validationEngine.settings.promptPosition == "centerRight") {
				callerleftPosition += callerWidth + 13;
			}
			
			if ($.validationEngine.settings.promptPosition == "bottomLeft") {
				callerHeight = $(caller).height();
				callerleftPosition = callerleftPosition;
				callerTopPosition = callerTopPosition + callerHeight + 15;
			}
			if ($.validationEngine.settings.promptPosition == "bottomRight") {
				callerHeight = $(caller).height();
				callerleftPosition += callerWidth - 30;
				callerTopPosition += callerHeight + 15;
			}
			$(divFormError).css({
				top: callerTopPosition,
				left: callerleftPosition,
				opacity: 0
			})
			return $(divFormError).animate({
				"opacity": 0.87
			}, function(){
				return true;
			});
			
		},
		updatePromptText: function(caller, promptText, type, ajaxed){
			linkTofield = $.validationEngine.linkTofield(caller);
			var updateThisPrompt = "." + linkTofield;
			if (type == "pass") {
				$(updateThisPrompt).addClass("greenPopup")
			} else {
				$(updateThisPrompt).removeClass("greenPopup")
			};
			if (type == "load") {
				$(updateThisPrompt).addClass("blackPopup")
			} else {
				$(updateThisPrompt).removeClass("blackPopup")
			};
			if (ajaxed) {
				$(updateThisPrompt).addClass("ajaxed")
			} else {
				$(updateThisPrompt).removeClass("ajaxed")
			};
			
			$(updateThisPrompt).find(".formErrorContent").html(promptText);
			callerTopPosition = $(caller).offset().top;
			inputHeight = $(updateThisPrompt).height();
			
			if ($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight") {
				callerHeight = $(caller).height();
				callerTopPosition = callerTopPosition + callerHeight + 15;
			}
			if ($.validationEngine.settings.promptPosition == "centerRight") {
				callerleftPosition += callerWidth + 13;
			}
			if ($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight") {
				callerTopPosition = callerTopPosition - inputHeight - 10;
			}
			$(updateThisPrompt).animate({
				top: callerTopPosition
			});
		},
		linkTofield: function(caller){
			linkTofield = $(caller).attr("id") + "formError";
			linkTofield = linkTofield.replace(/\[/g, "");
			linkTofield = linkTofield.replace(/\]/g, "");
			return linkTofield;
		},
		closePrompt: function(caller, outside){
			if (!$.validationEngine.settings) {
				$.validationEngine.defaultSetting()
			}
			if (outside) {
				$(caller).fadeTo("fast", 0, function(){
					$(caller).remove();
				});
				return false;
			}
			if (!ajaxValidate) {
				linkTofield = $.validationEngine.linkTofield(caller);
				closingPrompt = "." + linkTofield;
				$(closingPrompt).fadeTo("fast", 0, function(){
					$(closingPrompt).remove();
				});
			}
		},
		debug: function(error){
			if (!$("#debugMode")[0]) {
				$("body").append("<div id='debugMode'><div class='debugError'><strong>调试模式：验证引擎发生以下异常</strong></div></div>");
			}
			$(".debugError").append("<div class='debugerror'>" + error + "</div>");
		},
		submitValidation: function(caller){ // FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
			var stopForm = false;
			$.validationEngine.ajaxValid = true;
			$(caller).find(".formError").remove();
			var toValidateSize = $(caller).find("[class*=rule]").size();
			
			$(caller).find("[class*=rule]").each(function(){
				linkTofield = $.validationEngine.linkTofield(this);
				
				if (!$("." + linkTofield).hasClass("ajaxed")) { // DO NOT UPDATE ALREADY AJAXED FIELDS (only happen if no normal errors, don't worry)
					var validationPass = $.validationEngine.loadValidation(this);
					return (validationPass) ? stopForm = true : "";
				};
							});
			ajaxErrorLength = $.validationEngine.ajaxValidArray.length; // LOOK IF SOME AJAX IS NOT VALIDATE
			for (x = 0; x < ajaxErrorLength; x++) {
				if ($.validationEngine.ajaxValidArray[x][1] == false) {
					$.validationEngine.ajaxValid = false;
				}
			}
			if (stopForm || !$.validationEngine.ajaxValid) { // GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
				if ($.validationEngine.settings.animateSubmit) {
					var ofset = $(".formError:not('.greenPopup'):first").offset();
					destination = (ofset||{top:0,left:0}).top;
					$(".formError:not('.greenPopup')").each(function(){
						testDestination = $(this).offset().top;
						if (destination > testDestination) {
							destination = $(this).offset().top;
						}
					})
					$("html:not(:animated),body:not(:animated)").animate({
						scrollTop: destination
					}, 1100);
				}
				return true;
			} else {
				return false;
			}
		}
	}
})(jQuery);
